import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import AdminLayout from '@/layouts/AdminLayout.vue'

// 路由定义
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      guestOnly: true, // 仅未登录用户可访问
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: {
      guestOnly: true, // 仅未登录用户可访问
      title: '注册'
    }
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: {
      requiresAuth: false // 需要登录才能访问
    },
    children: [
      {
        path: '',
        name: 'AdminHome',
        component: () => import('@/views/admin/Home.vue'),
        meta: {
          title: '管理后台 - 首页',
          preload: 'loadHomeData' // 需要预加载的数据方法
        }
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: {
          title: '管理后台 - 数据面板',
          preload: 'loadDashboardData'
        }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/admin/User.vue'),
        meta: {
          title: '管理后台 - 用户管理',
          preload: 'loadUserData',
          roles: ['admin'] // 仅管理员可访问
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: {
      title: '页面未找到'
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫 - 权限控制
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const isAuthenticated = authStore.isAuthenticated

  // 检查是否需要登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    return next('/login')
  }

  // 检查是否仅限未登录用户访问
  if (to.meta.guestOnly && isAuthenticated) {
    return next('/admin')
  }

  // 检查角色权限
  if (to.meta.roles && !to.meta.roles.some(role => authStore.userRoles.includes(role))) {
    return next('/404')
  }

  next()
})

// 路由守卫 - 数据预加载
router.beforeResolve(async (to, from, next) => {
  try {
    const authStore = useAuthStore()
    
    // 如果需要预加载数据且用户已登录
    if (to.meta.preload && authStore.isAuthenticated) {
      const dataStore = useDataStore()
      // 调用对应的数据加载方法
      await dataStore[to.meta.preload]()
    }
    next()
  } catch (error) {
    console.error('数据预加载失败:', error)
    next()
  }
})

// 路由守卫 - 设置页面标题
router.afterEach((to) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
})

export default router
